import React , { Component, PropTypes } from "react"
import { connect } from 'react-redux'

import AppBar from "../common/AppBar"
import BlogItem from "./BlogItem"
import BlogItemDetail from "./BlogItemDetail"
import * as BlogAction from "../../redux/modules/blog"

import { FloatingActionButton } from 'material-ui';
import ContentAdd from 'material-ui/lib/svg-icons/content/add';

var config =require('config')

class BlogApp extends Component{
  static propTypes = {
    blogs: PropTypes.array.isRequired,
    blog: PropTypes.object.isRequired,
    dispatch: PropTypes.func.isRequired
  };

  static contextTypes={
    history: PropTypes.object.isRequired
  };

  constructor(props){
    super(props)
  }

  componentDidMount(){
    const {dispatch}=this.props;
    dispatch(BlogAction.fetchBlogs());
  }

  componentWillReceiveProps(nextProps){
    nextProps.user?'':(window.location.href=config.default.ctx+'/login');
  }

  getStyles() {
    return {
      main: {
        position: "absolute",
        right: 0,
        minHeight: "100%",
        background:"#eaeaea",
        left: "300px",
        width: "auto",
      },
      addContent: {
        position: 'fixed',
        right: 20,
        bottom: 20,
        zIndex: 100
      }
    };
  }

  deleteBlog(blog){
    const {dispatch}=this.props;
    dispatch(BlogAction.removeBlog(blog.id));
  }

  render(){
    const { history } = this.context;
    const {blogs,dispatch}=this.props;
    const styles=this.getStyles();
    return (
      <AppBar>
        <div style={styles.main}>
          {blogs.length>0?
          blogs.map((blog)=>
            <BlogItem key={blog.id} blog={blog}
              deleteBlog={this.deleteBlog.bind(this)}/>
          )
          :''}
        </div>
        <FloatingActionButton style={styles.addContent}
                              onTouchTap={()=>history.pushState(null,'/blog/new')}>
          <ContentAdd />
        </FloatingActionButton>
      </AppBar>
    );
  }
}


//export default AppComponent;
export default connect((state)=>({
  blogs:state.blog.blogs,
  blog:state.blog.blog,
  user:state.blog.user
}))(BlogApp);
